package com.jake.xpage.router;

import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jake.xpage.page.IPageAnimator;
import com.jake.xpage.page.XPage;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class XPageRouteMapper {
    @NonNull
    protected final Map<String, IPageLoader> mPageLoaders = new ConcurrentHashMap<>();
    private Callback mCallback;


    public void setCallback(Callback mCallback) {
        this.mCallback = mCallback;
    }


    public void openRoute(@NonNull XPageRoute route) {
        if (mCallback == null) {
            return;
        }
        final String uri = generatePageLoaderKey(route.module, route.url);
        IPageLoader pageLoader = mPageLoaders.get(uri);
        if (pageLoader != null && mCallback.getContext() != null) {
            XPage page = pageLoader.createPage(mCallback.getContext(), route);
            if (page != null) {
                mCallback.startPage(page, route.animator);
            }
        }
    }


    protected String generatePageLoaderKey(String moduleName, String url) {
        return moduleName + url;
    }

    public void register(String url, IPageLoader loader) {
        if (TextUtils.isEmpty(url) || loader == null) {
            return;
        }
        final String key = generatePageLoaderKey(moduleName(), url);
        mPageLoaders.put(key, loader);
    }

    protected abstract String moduleName();

    public void unregister(String url, IPageLoader loader) {
        if (TextUtils.isEmpty(url) || loader == null) {
            return;
        }
        final String key = generatePageLoaderKey(moduleName(), url);
        IPageLoader temp = mPageLoaders.get(key);
        if (temp == loader) {
            mPageLoaders.remove(key);
        }
    }

    public interface IPageLoader {
        XPage createPage(@NonNull Context context, @NonNull XPageRoute route);
    }

    public interface Callback {
        Context getContext();

        void startPage(@NonNull XPage page, @Nullable IPageAnimator animator);
    }
}
